<!-- views/dashboard/index.vue -->
<template>
  <div class="dashboard-container" v-loading="loading">
    <!-- 顶部操作栏 -->
    <div class="dashboard-header">
      <div class="left">
        <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
          <el-radio-button label="7">近7天</el-radio-button>
          <el-radio-button label="30">近30天</el-radio-button>
          <el-radio-button label="90">近90天</el-radio-button>
        </el-radio-group>
      </div>
      <div class="right">
        <el-button
            :icon="Refresh"
            circle
            @click="handleRefresh"
            :loading="refreshing"
        />
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col
          :span="6"
          v-for="item in dashboardData?.statistics"
          :key="item.title"
      >
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <span>{{ item.title }}</span>
            <el-tag :type="item.type">{{ item.change }}</el-tag>
          </div>
          <div class="card-number">{{ item.number }}</div>
          <div class="card-footer">
            较上周{{ item.trend > 0 ? '增长' : '下降' }} {{ Math.abs(item.trend) }}%
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 任务监控 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>爬虫任务监控</span>
              <el-tag>{{ dashboardData?.crawlerTasks?.length || 0 }} 个任务</el-tag>
            </div>
          </template>
          <el-table
              :data="dashboardData?.crawlerTasks"
              stripe
              style="width: 100%"
              :empty-text="loading ? '加载中...' : '暂无数据'"
          >
            <el-table-column prop="taskName" label="任务名称" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getTaskStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="endTime" label="最后运行时间" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>视频生成任务</span>
              <el-tag>{{ dashboardData?.videoTasks?.length || 0 }} 个任务</el-tag>
            </div>
          </template>
          <el-table
              :data="dashboardData?.videoTasks"
              stripe
              style="width: 100%"
              :empty-text="loading ? '加载中...' : '暂无数据'"
          >
            <el-table-column prop="title" label="视频标题" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getVideoStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import { useDashboardStore } from '@/stores/dashboard'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const store = useDashboardStore()
const { loading, refreshing, dashboardData } = storeToRefs(store)

// 时间范围选择
const timeRange = ref('7')

// 自动刷新定时器
let refreshTimer = null

// 获取数据
const fetchData = async () => {
  try {
    await store.fetchDashboardDataByDays(Number(timeRange.value))
  } catch (error) {
    ElMessage.error('获取数据失败：' + error.message)
  }
}

// 处理时间范围变化
const handleTimeRangeChange = (value) => {
  fetchData()
}

// 手动刷新
const handleRefresh = async () => {
  try {
    await store.refreshStatistics()
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新失败：' + error.message)
  }
}

// 获取任务状态对应的类型
const getTaskStatusType = (status) => {
  const types = {
    'SUCCESS': 'success',
    'PENDING': 'info',
    'FAILED': 'danger'
  }
  return types[status] || 'info'
}

// 获取视频状态对应的类型
const getVideoStatusType = (status) => {
  const types = {
    "待生成": 'info',
    '生成中': 'warning',
    '生成完成': 'success',
    '生成失败': 'danger'
  }
  return types[status] || 'info'
}

// 启动自动刷新
const startAutoRefresh = () => {
  // 每5分钟刷新一次
  refreshTimer = setInterval(fetchData, 5 * 60 * 1000)
}

// 组件挂载
onMounted(() => {
  fetchData()
  startAutoRefresh()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.card-number {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.card-footer {
  color: #909399;
  font-size: 12px;
}

.mt-4 {
  margin-top: 16px;
}

:deep(.el-card__header) {
  padding: 12px 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}
</style>